#!/bin/bash

###
### Program: timemachine
### File:    tm-onsite.sh
### Version: 2.0
### Owner:   raptus ag
### Author:  Florian S.
### Purpose:
###
### Collect data from the configured hosts, but do not archive
### Typically used on a central backup server
###

#
# standard stuff
#

if ! test "$#" -eq 1
then
    echo "Usage: $0 <config-file>"
    exit 1
fi

ME=`basename $0 | head -c -4`

SCRIPT=$(readlink -f $0)
SCRIPTPATH=`dirname $SCRIPT`
OLDDIR="`pwd`"
cd $SCRIPTPATH

CONFIGFILE="$1"
if ! test -f "$CONFIGFILE"
then
    echo "ERROR: Cannot find config file $CONFIGFILE"
    exit 1
fi

source "../config/defaults.conf"
source "$CONFIGFILE"
source "functions/locking.inc.sh"
source "functions/logging.inc.sh"
source "functions/errorcodes.inc.sh"

echo "Onsite Debuglog `date`" > $DEBUGONSITE 2>&1

#
# checking internal file structure
#

if ! test -d "$BACKUPDIR/$CUSTOMER/upload/$HOSTNAME/$JOBNAME"
then
    mkdir -p "$BACKUPDIR/$CUSTOMER/upload/$HOSTNAME/$JOBNAME" >> $DEBUGONSITE 2>&1
fi


#
# logfile stuff
#

log "-----------------------------------------------------------------------"
log "This is $CUSTOMER $HOSTNAME timemachine onsite backup"
log "Config $CONFIGFILE, Job $JOBNAME"
lock
if [ $? == 1 ];
then
        log "ERROR: Lockfile present, exiting."
        log "- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -"
        send "error"
        exit 1
fi

if ! test "$PINGCHECK" = "no"
then
    RES=`ping $HOSTNAME -c 1 | grep "1 received"`

    if test -z "$RES"
    then
        log "ERROR: Host is not present, or not pingable. Aborting."
        log "- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -"
        send "error"
        unlock
        exit 1
    fi
fi

#
# mount the volumes depending on OSTYPE
#

if ! test -d "$MOUNTDIR/$CUSTOMER/$JOBNAME"
then
    mkdir -p "$MOUNTDIR/$CUSTOMER/$JOBNAME" >> $DEBUGONSITE 2>&1
fi

if test "$OSTYPE" = "windows"
then
    MRET=`mount -t cifs "//$HOSTNAME/$WINSHARE" "$MOUNTDIR/$CUSTOMER/$JOBNAME" -o user="$WINUSER",pass="$WINPASS","$SAMBA_MOUNT_OPTS" 2>&1`
    if test -z "`mount | grep $MOUNTDIR/$CUSTOMER/$JOBNAME`"
    then
        MRET=`echo $MRET | grep "mount error"`
        log "ERROR: Failed to mount $WINSHARE on $HOSTNAME via CIFS, exiting."
        log "       Mount Error: $MRET"
        log "- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -"
        send "error"
        unlock
        exit 1
    fi

elif test "$OSTYPE" = "linux"
then
    if test -z "`which sshfs`"
    then
        log "ERROR: SSHFS seems not to be installed. Please install SSHFS."
        log "- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -"
        send "error"
        unlock
        exit 1
    fi

    sshfs $SSHFSUSR@$HOSTNAME:/ "$MOUNTDIR/$CUSTOMER/$JOBNAME" -o "$SSHFS_MOUNT_OPTS" >> $DEBUGONSITE 2>&1
    if test -z "`mount | grep $MOUNTDIR/$CUSTOMER/$JOBNAME`"
    then
        log "ERROR: Failed to mount / on $HOSTNAME via SSHFS, exiting."
        log "- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -"
        send "error"
        unlock
        exit 1
    fi


elif test true
then
    log "ERROR: No valid OSTYPE choosen, exiting."
    log "- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -"
    send "error"
    unlock
    exit 1
fi

BACKUPROOT="$MOUNTDIR/$CUSTOMER/$JOBNAME"


#
# rsync part
#

log "Starting backup..."

if test "$ONSITESPEED" = "0"
then
    SPEED=""
    LOGSPEED=""
else
    SPEED="--bwlimit=$ONSITESPEED"
    LOGSPEED="[limit: $ONSITESPEED KB/s]"
fi

MAILMESSAGE="success"
for i in "${INCLUDE_DIRS[@]}"
do

    SRC="$BACKUPROOT$i"
    DST="$BACKUPDIR/$CUSTOMER/upload/$HOSTNAME/$JOBNAME"

    # check if include dirs are there
    if ! test -d "$SRC"
    then
        log " --> $i could not be found! Please check your config file."
        MAILMESSAGE="partially failed"

    else
        EXCLUDE=""
        for j in "${EXCLUDE_LIST[@]}"
        do
            EXCLUDE="--exclude \"$j\" $EXCLUDE"
        done

        # rsync copy process
        # --archive         includes -r (recursive) -l (symlinks) -p (rights) -t (timestamps) -g (group) -o (owner) -D (special devices)
        # --delete-during   delete files not in source repo during copy process
        # --update          skip files that are newer on the receiver
        # --stats           show stats (necessary for speed output)
        # --verbose         verbose log (LOGFILEPATH/DEBUG/)
        # --human-readable  show stats in a human readable format

        if test -z "$RSYNCONSITE"; then RSYNCONSITE="--archive --delete-during --update --stats --verbose --human-readable"; fi

        if test -z "$NICELEVEL"; then NICELEVEL="18"; fi

        STATS=`nice -n $NICELEVEL rsync $RSYNCONSITE $EXCLUDE $SPEED "$SRC" "$DST" | tee $DEBUGONSITE 2>&1`
        RET=$?

        F=`echo "$STATS" | tail -n 14 | grep "Total file size" | cut -d " " -f 4`
        T=`echo "$STATS" | tail -n 14 | grep "Total transferred file size" | cut -d " " -f 5`

        # getting rsync error code
        rsync_status $RET
        log " --> $i finished. Status: $RSYNCMSG [Total: $F, Sent: $T] $LOGSPEED"

        if [[ "$RSYNCMSG" == *ERROR* ]]; then MAILMESSAGE="failed"; fi
    fi
done


#
# cleanup part
#

umount $MOUNTDIR/$CUSTOMER/$JOBNAME >> $DEBUGONSITE 2>&1
rmdir -p $MOUNTDIR/$CUSTOMER/$JOBNAME >> $DEBUGONSITE 2>&1

unlock
log "Backup done!"
log "-----------------------------------------------------------------------"

if [ "$ONSITEMAIL" == "off" ]; then ONSITEMAIL=""; fi

if ! test -z "$ONSITEMAIL"; then send "$MAILMESSAGE"; fi

# eof
